package com.zyz.demo.config;

import com.zyz.demo.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 验证token的合法性
        String userToken = request.getHeader("user_token");
        log.info("从header中获取token信息:\n"+userToken);
        Claims claims = JwtUtils.verify(userToken);
        if (claims == null) {
            log.warn("验证token失败,用户未登录");
            response.setStatus(401);
            response.getOutputStream().write("用户未登录".getBytes());
            return false;
        }
        return true;
    }
}
